package org.uim.cricket.storage.queries;

import org.uim.cricket.entities.match.CricketMatch;

public abstract class QueryGenerator implements QueryGeneratable {

	private CricketMatch match = null;
	
	public QueryGenerator(CricketMatch theMatch) {
		this.match = theMatch;
	}
	
	public void setMatch(CricketMatch match) {
		this.match = match;
	}
	
	public CricketMatch getMatch() {
		return match;
	}

	protected void appendQuery(StringBuilder query, String numeral, boolean appendComma) {
		query.append(numeral);
		if (appendComma) query.append(",");
	}
	
	protected void appendQuery(StringBuilder query, int numeral) {
		this.appendQuery(query, numeral, true);
	}
	
	protected void appendQuery(StringBuilder query, int numeral, boolean appendComma) {
		query.append(numeral);
		if (appendComma) query.append(",");
	}
	
	protected void appendQuery(StringBuilder query, String text, int maxLen, boolean addNull) {
		this.appendQuery(query, text, maxLen, addNull, true);
	}
	
	protected void appendQuery(StringBuilder query, String text, int maxLen, boolean addNull, boolean appendComma) {
		if (text == null) {
			query.append("NULL");
			if (appendComma) query.append(",");
			return;
		}
		if (text.length() > maxLen) {
			if (addNull) {
				query.append("NULL");
			} else {
				query.append("'").append(text.subSequence(0, maxLen - 1)).append("'");
			}
		} else {
			query.append("'").append(text).append("'");
		}
		if (appendComma) query.append(",");
	}
	
	protected String encodeSQL(String value) {
		if (value == null) return null;
		if (value.indexOf("'") >= 0) {
			return value.replaceAll("'", "\\\\'");
		}
		return value;
	}
	
}
